<?php
namespace application\datatypes;
use application\datatypes\DataType;
use application\utilities\Utility;

class ParentContent extends DataType {
	public static $name = 'ParentContent';
	public static $fields = array();
	
	public static function validate($field, $data, $results) {
		if($field->cf_required && !$data[$field->cf_column]) {
			$results['errors'][] = $field->cf_display_name.' is required.';
		}
		elseif($value = $data[$field->cf_column]) {
			$results['db_fields'][$field->cf_column] = $value;	
		}
		
		return $results;
	}
	
	public static function display($formElements) {
		if($formElements) {
			?>
			<fieldset class="single-field">
				<header><?=$formElements['display']?></header>
				<section class="inner">
				<?php if($description = $formElements['description']) : ?>
					<p class="form-description"><?=$description?></p>
				<?php endif;?>
				<?=$formElements['elements']['element']?>
				</section>
			</fieldset>
			<?php
		}
	}
	
	public static function build($field, $data) {
		global $concerto;
		// First, do we build at all? (Does this content type allow parents?) 
		$type = $field->cf_content_type;
		$allowedParents = unserialize(getOption('c'.$type.'_allowed_parents'));
		if($allowedParents && count($allowedParents)) {
			$value = $data[$field->cf_column];
			if(!$value) {
				$value = $concerto->unusedQueryVars['content_parent'];
				if($value) $disabled = TRUE;
			}
			$formElements = array('description'=>$field->cf_description, 'column'=>$field->cf_column, 'display'=>$field->cf_display_name, 'data_type'=>$field->cf_data_type);
			
			if($disabled) {
				$elements = '<input type="hidden" name="content_parent" value="'.$value.'"/>';
				$elements .= '<select disabled="disabled" name="'.$field->cf_column.'">';
			}
			else {
				$elements = '<select name="'.$field->cf_column.'">';
			}
			$parents = DB()->getResults("SELECT `content_id`, `content_title` FROM `cn_content` WHERE `content_type` IN (".Utility::sqlImplodedArray($allowedParents).")");
			foreach($parents as $parent) {
				if($value == $parent->content_id) {
					$elements .= '<option selected="selected" value="'.$parent->content_id.'">'.$parent->content_title.'</option>';
				}
				else {
					$elements .= '<option value="'.$parent->content_id.'">'.$parent->content_title.'</option>';
				}
			}
			$elements .= '</select>';
			
			$formElements['elements']['element'] = $elements;
			
			return $formElements;
		}
		else return FALSE;
	
	}
	
	public static function add() {
	
	}
	
	public static function save() {
	}
	
	public static function delete() {
	
	}
	
		
	
}
?>